import React, { useState, useEffect } from "react";
import { deleteList, getList } from "../../api";
import { Table, Row, Col, Button, Modal, Input, Space } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../store";

const types = ["全部", "正在阳", "没阳", "阳康", "复阳"];

const Home = () => {
  const listData = useSelector((state: RootState) => state.list.listData);
  const [wd, setWd] = useState("");
  const [type, setType] = useState("全部");
  const dispatch = useDispatch();
  // 请求列表数据
  const fetchList = async () => {
    try {
      const resp = await getList({ wd, type });
      // 将数据保存到仓库
      dispatch({ type: "setListData", payload: resp.data.data });
    } catch (error) {
      console.log("请求报错", error);
    }
  };
  // 封装函数 删除列表数据
  const handleDeleteList = async (id: string) => {
    Modal.confirm({
      title: "警告",
      content: "确认要删除吗？",
      async onOk() {
        const resp = await deleteList(id);
        fetchList();
      },
    });
  };

  useEffect(() => {
    fetchList();
  }, []);

  return (
    <div>
      <div>
        <Row style={{ margin: "10px 0", alignItems: "center" }}>
          <Col span={1}>搜索: </Col>
          <Col span={20}>
            <Input value={wd} onChange={(e) => setWd(e.target.value)}></Input>
          </Col>
        </Row>
        <Row style={{ margin: "10px 0", alignItems: "center" }}>
          <Col span={1}>类型: </Col>
          <Col span={20}>
            <Space>
              {types.map((v, i) => {
                return (
                  <Button
                    type={v === type ? "primary" : "default"}
                    key={i}
                    onClick={() => setType(v)}
                  >
                    {v}
                  </Button>
                );
              })}
            </Space>
          </Col>
        </Row>
        <Row style={{ margin: "10px 0", alignItems: "center" }}>
          <Col span={1}> </Col>
          <Col span={20}>
            <Button
              block
              type="primary"
              size="large"
              onClick={() => fetchList()}
            >
              查询
            </Button>
          </Col>
        </Row>
      </div>
      <div>
        <Row>
          {listData.map((v) => {
            return (
              <Col span={8} key={v.id}>
                <dl>
                  <dt>
                    <img src={v.image} alt="" />
                  </dt>
                  <dd>
                    <h3>{v.title}</h3>
                    <p>{v.word}</p>
                    <p>{v.type}</p>
                    <div>
                      <Button>编辑</Button>
                      <Button onClick={() => handleDeleteList(v.id)}>
                        删除
                      </Button>
                    </div>
                  </dd>
                </dl>
              </Col>
            );
          })}
        </Row>
      </div>
    </div>
  );
};

export default Home;
